# -*- coding: utf-8 -*-

from odoo import models, fields, api, modules
from odoo.exceptions import UserError
import datetime, base64

map_dict = {
    0: u'零',
    1: u'壹',
    2: u'贰',
    3: u'叁',
    4: u'肆',
    5: u'伍',
    6: u'陆',
    7: u'柒',
    8: u'捌',
    9: u'玖',
}

class MyModel(models.BaseModel):

    _auto = True                # automatically create database backend
    _register = False           # not visible in ORM registry, meant to be python-inherited only
    _abstract = False           # not abstract
    _transient = False

    def convert_integer_number_to_chinese_uppercase(self, number):
        '''整数部分转为大写'''
        uppercase = ''
        number_str = str(number)
        number_list = list(number_str)
        number_list.reverse()
        number_list = [int(item) for item in number_list]
        num_length = len(number_list)
        for i in range(0, num_length):
            num = number_list[i]
            if i == 0:
                if num == 0:
                    uppercase = u'圆'
                else:
                    uppercase = map_dict.get(num) + u'圆'
            elif i == 1:
                if num == 0:
                    if number_list[i - 1] != 0:
                        uppercase = map_dict.get(num) + uppercase
                else:
                    uppercase = map_dict.get(num) + u'拾' + uppercase
            elif i == 2:
                if num == 0:
                    if number_list[i - 1] != 0:
                        uppercase = map_dict.get(num) + uppercase
                else:
                    uppercase = map_dict.get(num) + u'佰' + uppercase
            elif i == 3:
                if num == 0:
                    if number_list[i - 1] != 0:
                        uppercase = map_dict.get(num) + uppercase
                else:
                    uppercase = map_dict.get(num) + u'仟' + uppercase
            elif i == 4:
                if num == 0:
                    uppercase = u'万' + uppercase
                else:
                    uppercase = map_dict.get(num) + u'万' + uppercase
            elif i == 5:
                if num == 0:
                    if number_list[i - 1] != 0:
                        uppercase = map_dict.get(num) + uppercase
                else:
                    uppercase = map_dict.get(num) + u'拾' + uppercase
            elif i == 6:
                if num == 0:
                    if number_list[i - 1] != 0:
                        uppercase = map_dict.get(num) + uppercase
                else:
                    uppercase = map_dict.get(num) + u'佰' + uppercase
            elif i == 7:
                if num == 0:
                    if number_list[i - 1] != 0:
                        uppercase = map_dict.get(num) + uppercase
                else:
                    uppercase = map_dict.get(num) + u'仟' + uppercase
            elif i == 8:
                if num == 0:
                    pass
                else:
                    uppercase = map_dict.get(num) + u'亿' + uppercase
            else:
                uppercase = u'数字过大'
        return uppercase

    def convert_decimal_to_uppercase(self, num_str):
        '''浮点数转为中文大写'''
        uppercase = ''
        num_list = list(num_str)
        for i in range(0, len(num_list)):
            num = int(num_list[i])
            if i == 0 and num:
                uppercase += map_dict.get(num) + u'角'
            elif i == 1 and num:
                uppercase += map_dict.get(num) + u'分'
        return uppercase

    def convert_number_to_chinese_uppercase(self, number):
        '''将数字转为中文大写 最大到千万级别'''
        num_list = str(number).split('.')
        if len(num_list) == 1:
            result = self.convert_integer_number_to_chinese_uppercase(int(num_list[0]))
            result += u'整'
            return result
        elif len(num_list) == 2:
            integer_result = self.convert_integer_number_to_chinese_uppercase(num_list[0])
            float_result = self.convert_decimal_to_uppercase(num_list[1])
            if not float_result:
                float_result = u'整'
            result = integer_result + float_result
            return result

    @api.model
    def return_print_cols(self, fields_dic):
        '''传入字段列表 返回打印需要的cols'''
        data = []
        fields_info = self.fields_get()
        for (field, field_info) in fields_dic.items():
            if field_info.has_key('field_name'):
                field_name = field_info['field_name']
            else:
                field_name = field
            if field_info.has_key('type'):
                field_type = field_info['type']
            else:
                field_type = fields_info.get(field, {}).get('type', '')

            if field_type == 'integer':
                data.append({"type": 'integer', "size": 0, "name": field_name, "required": False})
            elif field_type == 'float':
                data.append({"type": 'float', "size": 0, "name": field_name, "required": False})
            elif field_type in ['char', 'text', 'date', 'datetime']:
                data.append({"type": 'str', "size": 255, "name": field_name, "required": False})
            elif field_type == 'selection':
                for item in fields_info.get(field).get('selection', []):
                    new_field_name = field_name + '_' + item[0]
                    data.append({"type": 'Blob', "size": 255, "name": new_field_name, "required": False})
            elif field_type == 'image':
                num = field_info.get('num', 1)
                for i in range(0, num):
                    new_field_name = u'%s_%d' % (field_name, i + 1)
                    data.append({"type": 'Blob', "size": 255, "name": new_field_name, "required": False})
            elif field_type == 'many2one':
                data.append({"type": 'str', "size": 255, "name": field_name, "required": False})
        return data

    @api.multi
    def return_print_data(self, fields_dic):
        '''传入字段列表 返回打印需要的data'''
        data = []
        fields_info = self.fields_get()
        for record in self:
            record_data = {}
            for (field, field_info) in fields_dic.items():
                if field_info.has_key('type'):
                    field_type = field_info['type']
                else:
                    field_type = fields_info.get(field, {}).get('type', '')
                if field_info.has_key('field_name'):
                    field_name = field_info['field_name']
                else:
                    field_name = field

                if field_type in ['integer', 'float', 'date', 'datetime']:
                    record_data[field_name] = getattr(record, field) or 0
                elif field_type in ['char', 'text']:
                    record_data[field_name] = getattr(record, field) or ''
                elif field_type == 'selection':
                    for item in fields_info.get(field).get('selection', []):
                        new_field_name = field_name + '_' + item[0]
                        if getattr(record, field) == item[0]:
                            record_data[new_field_name] = yes_img_content
                        else:
                            record_data[new_field_name] = no_img_content
                elif field_type == 'image':
                    imgs = getattr(record, field)
                    if not imgs:
                        continue
                    num = field_info.get('num', 1)
                    img_data = imgs[0:num].return_image_b64_data()
                    for i in range(0, len(img_data)):
                        new_field_name = u'%s_%d' % (field, i + 1)
                        record_data[new_field_name] = img_data[i]
                elif field_type == 'many2one':
                    record_data[field_name] = getattr(record, field).name or ''
            if record_data:
                data.append(record_data)
        return data

    @api.multi
    def return_print_table_data(self, fields_dic):
        '''传入字段信息 返回打印需要的格式数据'''
        return {
            'Name': self._name.replace('.', '_'),
            'Cols': self.return_print_cols(fields_dic),
            'Data': self.return_print_data(fields_dic),
        }

    @api.multi
    def judge_page_readonly(self, model, context):
        '''判断前端页面是否可以编辑'''
        self.ensure_one()
        if model == 'follow.record':
            return True
        elif model == 'plan':
            if self.state == 'done':
                return True
            else:
                return False
        elif model == 'sale.order':
            if self.quotation_state == 'done':
                return True
            else:
                return False
        elif model == 'contract':
            if self.state == 'done':
                return True
            else:
                return False
        elif model == 'project.task':
            if self.state == 'done':
                return True
            else:
                return False
        elif model == 'train.debug':
            if self.state == 'done':
                return True
            else:
                return False
        elif model == 'check.order':
            if self.state == 'done':
                return True
            else:
                return False
        else:
            return False

    @api.model
    def return_datetime_point(self, stop_datetime, minutes_interval, include_stop_datetime):
        '''返回stop_datetime往前minutes_interval分钟的时间点  '''
        if stop_datetime:
            if type(stop_datetime) is not datetime.datetime:
                try:
                    stop_datetime = datetime.datetime.strptime(stop_datetime, "%Y-%m-%d %H:%M")
                except:
                    stop_datetime = datetime.datetime.strptime(stop_datetime, "%Y-%m-%d %H:%M:%S")
        else:
            stop_datetime = datetime.datetime.now()
        start_datetime = stop_datetime - datetime.timedelta(minutes=minutes_interval)
        datetime_list = []
        if include_stop_datetime:
            while start_datetime <= stop_datetime:
                datetime_list.append(start_datetime.strftime("%Y-%m-%d %H:%M"))
                start_time = start_time + datetime.timedelta(minutes=1)
        else:
            while start_datetime < stop_datetime:
                datetime_list.append(start_datetime.strftime("%Y-%m-%d %H:%M"))
                start_datetime += datetime.timedelta(minutes=1)
        return datetime_list


    @api.model
    def ymrhm_write(self, datetime_val):
        '''将东八区的时间转为utc时间'''
        if not datetime_val:
            return ''
        try:
            datetime_val = datetime.datetime.strptime(datetime_val, "%Y-%m-%d %H:%M")
        except:
            try:
                datetime_val = datetime.datetime.strptime(datetime_val, "%Y/%m/%d %H:%M")
            except:
                raise UserError(u'日期格式错误')
        datetime_val = datetime_val - datetime.timedelta(hours=8)
        datetime_str = datetime_val.strftime("%Y-%m-%d %H:%M:%S")
        return datetime_str

    @api.model
    def ymrhms_write(self, datetime_val):
        '''将东八区的时间转为utc时间'''
        if not datetime_val:
            return ''
        try:
            datetime_val = datetime.datetime.strptime(datetime_val, "%Y-%m-%d %H:%M:%S")
        except:
            try:
                datetime_val = datetime.datetime.strptime(datetime_val, "%Y/%m/%d %H:%M:%S")
            except:
                raise UserError(u'日期格式错误')
        datetime_val = datetime_val - datetime.timedelta(hours=8)
        datetime_str = datetime_val.strftime("%Y-%m-%d %H:%M:%S")
        return datetime_str

    @api.model
    def ymrhm_show(self, datetime_val):
        '''将utc时间转为东八区时间'''
        if not datetime_val:
            return ''
        try:
            datetime_val = datetime.datetime.strptime(datetime_val, "%Y-%m-%d %H:%M:%S")
            datetime_val = datetime_val + datetime.timedelta(hours=8)
            datetime_str = datetime_val.strftime("%Y-%m-%d %H:%M")
            return datetime_str
        except:
            return ''

    @api.multi
    def app_get_field_value(self, field):
        '''返回字段值 date和datetime类型要+8h，selection返回对应值'''
        return

    @api.multi
    def get_selection_string(self, field):
        '''返回selection字段string值'''
        selection = self.fields_get().get(field, {}).get('selection', {})
        field_val = getattr(self, field)
        for item in selection:
            if item[0] == field_val:
                return item[1]
        return ''

    @api.model
    def get_field_selection(self, field):
        '''返回字段selection选项'''
        fields_info = self.fields_get()
        selection = []
        if fields_info.has_key(field) and fields_info[field].get('type') == 'selection':
            for item in fields_info[field].get('selection'):
                selection.append({
                    'key': item[0],
                    'value': item[1],
                })
        return selection

    @api.model
    def get_all_area(self):
        '''获取区域数据'''
        data = []
        province_records = self.env['province'].search([])
        for province in province_records:
            if province.no_city:
                county_list = []
                for county in province.county_ids:
                    county_list.append({
                        'id': county.id,
                        'name': county.name,
                    })
                province_data = {
                    'id': province.id,
                    'name': province.name,
                    'county': county_list,
                }
            else:
                city_list = []
                for city in province.city_ids:
                    county_list = []
                    for county in city.county_ids:
                        county_list.append({
                            'id': county.id,
                            'name': county.name,
                        })
                    city_list.append({
                        'id': city.id,
                        'name': city.name,
                        'county': county_list,
                    })
                province_data = {
                    'id': province.id,
                    'name': province.name,
                    'city': city_list,
                }
            data.append(province_data)
        return data

    @api.model
    def get_area_data_new(self):
        '''获取区域数据 id name 0 全部
        http://localhost:8069/BigScreenSelect?model=res.partner&context={'page':'address'}
        '''
        data = [{
            'id': 0,
            'name': u'全部',
        }]
        province_records = self.env['province'].search([])
        for province in province_records:
            if province.no_city:
                county_list = [{
                    'id': 0,
                    'name': u'全部',
                }]
                for county in province.county_ids:
                    county_list.append({
                        'id': county.id,
                        'name': county.name,
                    })
                province_data = {
                    'id': province.id,
                    'name': province.name,
                    'county': county_list,
                }
            else:
                city_list = [{
                    'id': 0,
                    'name': u'全部',
                }]
                for city in province.city_ids:
                    county_list = [{
                        'id': 0,
                        'name': u'全部',
                    }]
                    for county in city.county_ids:
                        county_list.append({
                            'id': county.id,
                            'name': county.name,
                        })
                    city_list.append({
                        'id': city.id,
                        'name': city.name,
                        'county': county_list,
                    })
                province_data = {
                    'id': province.id,
                    'name': province.name,
                    'city': city_list,
                }
            data.append(province_data)
        return data

    @api.model
    def get_today_start_time_end_time(self):
        '''获取北京时间今天，对应的utc时间的起止时间'''
        utc_now_time = datetime.datetime.now()
        beijing_now_time = utc_now_time + datetime.timedelta(hours=8)
        beijing_today_start_str = beijing_now_time.strftime("%Y-%m-%d 00:00:00")
        beijing_today_start = datetime.datetime.strptime(beijing_today_start_str, "%Y-%m-%d %H:%M:%S")
        utc_today_start = beijing_today_start - datetime.timedelta(hours=8)
        utc_today_start_str = utc_today_start.strftime("%Y-%m-%d %H:%M:%S")
        utc_today_end = utc_today_start + datetime.timedelta(days=1)
        utc_today_end_str = utc_today_end.strftime("%Y-%m-%d %H:%M:%S")
        return {
            'utc_today_start_str': utc_today_start_str,
            'utc_today_end_str': utc_today_end_str,
        }

    ###################### 创建编辑 ##########################

    @api.model
    def address_analyse(self, vals):
        '''返回省 市 区'''
        if vals.has_key('province_id'):
            if vals['province_id']:
                province = self.env['province'].search([('name', '=', vals['province_id'])], limit=1)
                if province:
                    vals['province_id'] = province.id
                else:
                    raise UserError(u'没有找到为%s' % vals['province_id'])
            else:
                vals['province_id'] = False
        if vals.has_key('city_id'):
            if vals['city_id']:
                city = self.env['city'].search([('name', '=', vals['city_id'])], limit=1)
                if city:
                    vals['city_id'] = city.id
                else:
                    raise UserError(u'没有找到%s' % vals['city_id'])
            else:
                vals['city_id'] = False
        if vals.has_key('county_id'):
            if vals['county_id']:
                county = self.env['county'].search([('name', '=', vals['county_id'])], limit=1)
                if county:
                    vals['county_id'] = county.id
                else:
                    raise UserError(u'没有找到%s' % vals['county_id'])
            else:
                vals['county_id'] = False
        return vals

    def img_field_analyse(self, obj, field, val, domain):
        '''图片字段解析'''
        img_val = []
        for url in val.get('add', []):
            domain['url'] = url
            img_val.append([0, False, domain])
        if val.get('delete', []):
            del_imgs = getattr(obj, field).filtered(lambda r: r.url in val['delete'])
            if del_imgs:
                img_val += [[2, id, False] for id in del_imgs.ids]
        return img_val

    @api.model
    def api_field_analyse(self, vals, context):
        '''把前端传入的数据解析成odoo直接保存的格式'''
        new_vals = {}
        page_fields_info = self.get_page_fields_info(context)
        for (field, val) in vals.items():
            if not page_fields_info.has_key(field):
                new_vals[field] = val
                continue
            field_type = page_fields_info[field]['type']
            if field_type == 'image':
                domain = page_fields_info[field].get('domain', {})
                new_vals[field] = self.img_field_analyse(self, field, val, domain)
            elif field_type == 'one2many':
                if not val:
                    continue
                relation_obj = self.env[page_fields_info[field]['relation']]
                one2many_val = []
                one2many_fields_info = page_fields_info[field]['fields']
                #create
                for item in val.get('add', []):
                    value = {}
                    for (child_field, child_val) in item.items():
                        if not one2many_fields_info.has_key(child_field):
                            value[child_field] = child_val
                            continue
                        child_field_info = one2many_fields_info[child_field]
                        if child_field_info['type'] == 'image':
                            domain = child_field_info.get('domain', {})
                            value[child_field] = self.img_field_analyse(relation_obj, child_field, child_val, domain)
                        else:
                            value[child_field] = child_val
                    one2many_val.append([0, False, value])
                #write
                for item in val.get('edit', []):
                    value = {}
                    id = item.get('id', False)
                    if not id:
                        continue
                    relation_obj = relation_obj.browse(id)
                    for (child_field, child_val) in item.items():
                        if not one2many_fields_info.has_key(child_field):
                            continue
                        child_field_info = one2many_fields_info[child_field]
                        if child_field_info['type'] == 'image':
                            domain = child_field_info.get('domain', {})
                            value[child_field] = self.img_field_analyse(relation_obj, child_field, child_val, domain)
                        else:
                            value[child_field] = child_val
                    if id:
                        one2many_val.append([1, id, value])
                #delete
                for id in val.get('delete', []):
                    one2many_val.append([2, id, False])
                new_vals[field] = one2many_val
            else:
                new_vals[field] = val
        return new_vals
#创建、编辑无需处理的字段类型：integer float text selection many2one boolean
#创建、编辑需要处理的字段类型：image one2many

    @api.model
    def my_create(self, vals, context):
        '''创建'''
        # vals = self.address_analyse(vals)
        vals = self.api_field_analyse(vals, context)
        result = self.create(vals)
        return result.id

    @api.multi
    def my_write(self, vals, context):
        '''编辑'''
        # vals = self.address_analyse(vals)
        vals = self.api_field_analyse(vals, context)
        result = self.write(vals)
        return result

    ############################ 查询  ####################################

    @api.model
    def get_page_fields_info(self, context):
        return {}



    @api.model
    def add_field_info(self, field, info):
        '''递归调用'''
        if info.get('type') == 'selection':
            odoo_field_info = self.fields_get().get(field, {})
            if odoo_field_info.get('type', '') == 'many2one':
                pass
                # obj = self.env[odoo_field_info.get('relation')]
                # domain = info.get('domain', [])
                # selection = []
                # for obj_record in obj.search(domain):
                #     relation_field = info.get('relation_field')
                #     if relation_field:
                #         selection.append({
                #             'key': obj_record.id,
                #             'value': obj_record.name,
                #             relation_field: getattr(obj_record, relation_field)
                #         })
                #     else:
                #         selection.append({
                #             'key': obj_record.id,
                #             'value': obj_record.name,
                #         })
                # info['selection'] = selection
            elif odoo_field_info.get('type', '') == 'selection':
                info['selection'] = self.get_field_selection(field)
        elif info.get('type') == 'one2many':
            obj = self.env[info['relation']]
            for (child_field, child_info) in info['fields'].items():
                obj.add_field_info(child_field, child_info)

    @api.model
    def get_many2one_selection(self, domain, relation_field):
        records = self.search(domain)
        selection = [{'key': record.id, 'value': record.name, relation_field: getattr(record, relation_field) or ''} for record in records]
        return selection

    @api.model
    def page_initial(self, context):
        '''获取页面初始化信息。比如selection选项、字段显示值、是否为必填'''
        fields_info = self.get_page_fields_info(context)
        for (field, info) in fields_info.items():
            self.add_field_info(field, info)
        return fields_info

